package ms.unicorn.modellanguage;

import java.lang.reflect.Field;
import java.util.Map;
import java.util.TreeMap;

import ms.unicorn.ui.decorators.IDecorator;
import ms.unicorn.util.ConfigUtil;
import ms.unicorn.util.ErrorHandler;
import ms.unicorn.util.TypeConvert;

import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.draw2d.ColorConstants;
import org.eclipse.draw2d.IFigure;
import org.eclipse.swt.graphics.Color;

public class DecoratorProxy {
	//private IConfigurationElement config;
	private IDecorator decor;
	private Map<String, String> params = new TreeMap<String, String>();
	private String constraint;
	
	public DecoratorProxy(IConfigurationElement config) {
		//this.config = config;
		constraint = ConfigUtil.get(config, "constraint", "");
		try {
			decor = (IDecorator) config.createExecutableExtension("decorator");
		} catch (CoreException e) {
			ErrorHandler.handleException(e);
		}
		for(IConfigurationElement child: config.getChildren("param"))
			params.put(child.getAttribute("name"), child.getAttribute("value"));
	}

	public void createDecoration(IFigure target) {
		if (decor != null)
			decor.createDecoration(target, this);
	}

	public String getConstraint() {
		return constraint;
	}
	
	public String getParam(String name, String defaultValue) {
		return params.containsKey(name) ? params.get(name) : defaultValue;
	}
	
	public int getIntParam(String name, int defaultValue) {
		return params.containsKey(name) ? TypeConvert.toInt(params.get(name), defaultValue) : defaultValue;
	}
	
	public boolean getBooleanParam(String name, boolean defaultValue) {
		return params.containsKey(name) ? TypeConvert.toBool(params.get(name)) : defaultValue;
	}
	
	public Color getColorParam(String name, Color defaultValue) {
		try {
			Field field = ColorConstants.class.getField(params.get(name));
			return (Color) field.get(null);
		} catch (Exception e) {
			return defaultValue;
		} 
	}
}